package view.msg
{
	import business.MsgDelegate;
	
	import events.MyLogEvent;
	
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.collections.XMLListCollection;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.DataGrid;
	import mx.controls.LinkButton;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	import mx.events.ItemClickEvent;
	import mx.events.PropertyChangeEvent;
	import mx.formatters.DateFormatter;
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	
	
	[Bindable]
	public class SiteMessageClass extends VBox
	{
		public var protoTypesSrc:XML;
		public var protoTypes:XMLListCollection;
		public var msgs:ArrayCollection;
        public var page:int;
        public var pagecnt:int;
        public var pageVolume:int;
        public var pageIndices:Array;
        public var protos:Object;
        
        public var myGrid:DataGrid;
        private var delegate:MsgDelegate;
        private var updatedItems:Dictionary;
        private var newItems:Dictionary;
        private var newId:Number;
        private var logId:String = '-1'; 
        
		public function SiteMessageClass()
		{
            delegate = new MsgDelegate(this);
            delegate.getConfigs();
            this.page = 0;			
            updatedItems = new Dictionary;
            newItems = new Dictionary;
            newId = 1;
		}

        public function fault(error:FaultEvent,token:Object = null):void
        {
            Alert.show(error.fault.faultString,'error');
        }
        
        private function makePageIndices():void
        {
            var a:Array = new Array();
            a.push({page:0,desc:'首页'});         
            a.push({page:page-1,desc:'前一页'});           
            a.push({page:page+1,desc:'后一页'});
            a.push({page:pagecnt-1,desc:'尾页'});
            this.pageIndices = a;
        }
        
        public function clickHandler(event:ItemClickEvent):void 
        {
        	if ( event.index == 0 ) // add site message
            {
                //this.delegate.addSiteMessage();
                var item:Object = new Object;
                item.id = "N"+newId;
                newId = newId + 1;
                item.proto = 0;
                var date:Date = new Date;
                item.time = date.getTime()/1000;
                item.expire = 0;
                item.title = '';
                item.content = '';
                item.isNew = true;
                this.newItems[item.id] = item;
                this.msgs.addItemAt(item, 0);    
            }
            else if ( event.index == 1 ) // select all
            {
                for each ( var a:Object in this.msgs )
                {
                    a.selected = true;
                }
                
                dispatchEvent(PropertyChangeEvent.createUpdateEvent
                    (this,'msgs',null,this.msgs));
            }
            else if ( event.index == 2 ) // deselect all
            {
                for each ( var a1:Object in this.msgs )
                {
                    a1.selected = false;
                }
                
                dispatchEvent(PropertyChangeEvent.createUpdateEvent
                    (this,'msgs',null,this.msgs));
            }   
            else if ( event.index == 3 ) // del selected
            {
                var ids:Array = new Array;
                
                for each ( var a2:Object in this.msgs )
                {
                    if ( a2.selected )
                    {
                        ids.push(a2.id);
                        a2.selected = false;
                    }
                }
                
                if ( ids.length )
                {
                    dispatchEvent(PropertyChangeEvent.createUpdateEvent
                        (this,'msgs',null,this.msgs));
                    
                    //var vardata:Object = new Object();
                    //vardata.page = page;
                    //vardata.ids = ids;
					//LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goRemoveSiteMessages);
					LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.MESSAGE, LogUtil.DEL, ids.toString());                    
                    this.delegate.removeSiteMessages(this.page,ids);
                }   
            }
            else if (event.index == 4) // save
            {
                for(var idx:String in this.newItems)
                {
                    var item1:Object  = this.newItems[idx];
					//LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goAddSiteMessage);
					//LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.MESSAGE, LogUtil.ADD, item1);                    
                    LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.MESSAGE, LogUtil.ADD, item1, '', '', true);
                    this.delegate.addSiteMessage(item1);                    
                }
                this.newItems = new Dictionary;
                
                for(var idx1:String in this.updatedItems)
                {
                	var items:Dictionary  = this.updatedItems[idx1];
//                	var item:Object = this.msgs[idx];
//                	if(item.hasOwnProperty('isNew') && item.isNew) {
//                		continue;
//                	}
                	
                	if (idx1.substr(0,1) == 'N'){
                		continue;
                	}
	                for each(var updated:Object in items)
	                {
	                    delegate.updateSiteMessage(updated); 
	                    
	                    //TODO, 流程不太对
						LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.MESSAGE, LogUtil.UPDATE, updated, '', '', true);                    
	                }
                }  
                this.updatedItems = new Dictionary;         	
            }
        }
        
/*         private function goRemoveSiteMessages(event:MyLogEvent):void
        {
			event.target.removeEventListener(MyLogEvent.LOGREADY, goRemoveSiteMessages);
			this.logId = event.logId;
			this.delegate.removeSiteMessages(event.record.page,event.record.ids);
        }
        
        private function goAddSiteMessage(event:MyLogEvent):void
        {
			event.target.removeEventListener(MyLogEvent.LOGREADY, goAddSiteMessage);
			this.logId = event.logId;
			this.delegate.addSiteMessage(event.record);        
        } */
        
        public function goto(evt:MouseEvent):void
        {
            var page:int = LinkButton(evt.currentTarget).data.page;
            delegate.getSiteMessages(page);
        }
        
        public function getConfigsResult(result:Object, token:Object = null):void
        {
            delegate.getSiteMessages(this.page);
            
            result = result.result;
            
            // 协议名称
            this.protoTypesSrc = <root />;
            
            for each ( var a:Object in result.protos.names )
            {
            	switch(result.protos.macro[a.id])
            	{
            	case 'PROTO_DEFAULT':
                case 'PROTO_ACTIVITY':  // 暂无
                case 'PROTO_NOTIFY':
                case 'PROTO_NEW_VERSION': // 暂无
                case 'PROTO_NEW_GUILD': // 暂无
                case 'PROTO_BROADCAST'://爱拍播报
                    break;
                default:
                    continue;
            	}
                var proto:XML = <proto></proto>;
                proto.@id = a.id;
                proto.@name = a.name;
                this.protoTypesSrc.appendChild(proto);
            }
            
            this.protoTypes = new XMLListCollection(this.protoTypesSrc.proto);
            
            this.protos = result.protos;
            this.pageVolume = result.messagePageVolume;
        }
        
        private function onDataChanged(event:CollectionEvent):void
        {
            var item:Object;
            var updated:Object;
            var i:int;

            if(event.kind == CollectionEventKind.UPDATE)
            {
                for(i = 0; i <event.items.length; i++)
                {
                    item = event.items[i];
                        
                    if ( item.property == 'selected')
                        continue;

                    if (!this.updatedItems.hasOwnProperty(item.source.id))
                        this.updatedItems[item.source.id] = new Dictionary;

                    updated = new Object;
                    updated.id = item.source.id;
                    updated.property = item.property;
                    updated.value = item.source[item.property];
                    this.updatedItems[item.source.id][item.property] = updated;                    
                }
            }
        }
        
        private function checkResult(result:Object):Boolean
        {
        	result = result.result;
            if ( result.code )
            {
                var fault:Fault = new Fault('',result.msg);
                var error:FaultEvent = new FaultEvent('fault',false,true,fault);
                this.fault(error);
                return false;
            }        
            return true;	
        }
        
        public function getSiteMessagesResult(result:Object, token:Object=null):void
        {
            if (!this.checkResult(result))
                return;
                
            result = result.result;
            
            this.msgs = new ArrayCollection(result.msgs);
            this.page = result.page;
            this.pagecnt = result.pagecnt;
            
            this.makePageIndices();         
            
            this.msgs.addEventListener(CollectionEvent.COLLECTION_CHANGE, onDataChanged);
        }
        
        public function removeSiteMessagesResult(result:Object, token:Object = null):void
        {
            if (!this.checkResult(result))
                return;
            LogUtil.getInstance().setOptSuccessd(logId);                
            this.getSiteMessagesResult(result, token);
        }
        
        public function updateSiteMessageResult(result:Object, token:Object = null):void
        {
            if (!this.checkResult(result))
                return;            
            this.msgs.addEventListener(CollectionEvent.COLLECTION_CHANGE, onDataChanged);
        }
        
        public function addSiteMessageResult(result:Object, token:Object = null):void
        {
            if (!this.checkResult(result))
                return;
            
            LogUtil.getInstance().setOptSuccessd(logId);
            data = result.result;
            for each(var item:Object in this.msgs)
            {
            	if(item.id == data.oldId) {
            	   item.id = data.newId;
            	}
            	this.newItems[item.oldId] = null;
            	delete this.newItems[item.oldId];
            }
            this.msgs.addEventListener(CollectionEvent.COLLECTION_CHANGE, onDataChanged);
        }
        
        public function protoTypeLabel(item:Object, column:DataGridColumn):String
        {
            if ( this.protoTypesSrc )
                return this.protoTypesSrc.proto.(@id==item[column.dataField]).@name;
            else
                return '';
        }
        
        public function timeTypeLable(item:Object, column:DataGridColumn):String
        {
        	var v:String = item[column.dataField];
        	var t:Date = new Date();
        	t.setTime(parseInt(v, 10)*1000);
        	var formatter:DateFormatter = new DateFormatter();
        	formatter.formatString = 'YYYY/MM/DD J:N:S';
        	return formatter.format(t);
        }
        
        public function contentLable(item:Object, column:DataGridColumn):String
        {
	        	var retval:String;
	        	var proto:String = this.protos.macro[ item['proto'] ];
	        	var value:Object = item[column.dataField];	  
	        	if (value == null) 
	        	  return 'xxyy'; 	        	

	            switch(proto)
	            {
	            case 'PROTO_DEFAULT':
	                return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_ADD_FRIEND_REQUEST':
					return value.hasOwnProperty('adword') ? value.adword : '';
					break;
				case 'PROTO_ACTIVITY':  // 暂无
				     return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_ASSET_DELETE': // 暂无
	                 return value.hasOwnProperty('title') ? value.title : '';			
				     break;
				case 'PROTO_NOTIFY':
				     return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_NEW_VERSION': // 暂无
	                 return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_NEW_GUILD': // 暂无
	                 return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_USER_COMMENT':
	                 return value.hasOwnProperty('adword') ? value.adword : '';
				     break;
				case 'PROTO_RE_USER_COMMENT':
	                 return value.hasOwnProperty('adword') ? value.adword : '';
	                 break;
				case 'PROTO_ASSET_COMMENT':
	                 return value.hasOwnProperty('adword') ? value.adword : '';
	                 break;
				case 'PROTO_RE_ASSET_COMMENT':
	                 return value.hasOwnProperty('adword') ? value.adword : '';
	                 break;
				case 'PROTO_USER_LEVEL_UP':
	                 return value.level;
	                 break;
				case 'PROTO_USER_SEND_FLOWER':
				     var assetName:String = value.hasOwnProperty('assetName') ? value.assetName : '';
				     var assetUrl:String = value.hasOwnProperty('assetUrl') ? value.assetUrl : '';
	                 return assetName + ' ' + assetUrl;
	                 break;
	            }	            
	            return '';
        }
        
//        public function timeTipFunction(hd:HitData):String
//        {
//            return '格式: 年/月/日 时:分:秒';
//        }
	}
}